<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
	#div1{width:100px; height: 100px; background-color: red;position: absolute;}
	</style>
	<script type="text/javascript">
	window.onload = function (){
		var oDiv = document.getElementById('div1');

		oDiv.onmousedown = function (ev){
			var ev = ev || event;

			var disX = ev.clientX - this.offsetLeft;
			var disY = ev.clientY - this.offsetTop;

			document.onmousemove = function (ev){
				var ev = ev || event;

				var L = ev.clientX -disX;
				var T = ev.clientY - disY;

				if (L < 0) {
					L = 0;
				}else if(L > document.documentElement.clientWidth - oDiv.offsetWidth){
					L = document.documentElement.clientWidth - oDiv.offsetWidth;
				}

				//如果不单独分成两块会出现问题
				if (T < 0) {
					T = 0;
				}else if(T > document.documentElement.clientHeight - oDiv.offsetHeight){
					T = document.documentElement.clientHeight - oDiv.offsetHeight;
				};

			 	oDiv.style.left = L + 'px';
			 	oDiv.style.top = T + 'px';
			 }

			 document.onmouseup = function (){

			 	document.onmouseup = document.onmousemove = null;

			 	oDiv.releaseCapture && oDiv.releaseCapture();
			 }

			 this.setCapture && this.setCapture();
			 return false;
		}			
	}
	</script>
</head>
<body>
	<div id="div1"></div>
</body>
</html>